﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;

namespace Zyg.SSO.Web
{
    public class BasePage : System.Web.UI.Page
    {
        private Zyg.SSO.Core.Business.Account account;
        protected Zyg.SSO.Core.Business.Account Account { get { return account; } set { account = value; } }

        protected void Page_Init(object sender, EventArgs e)
        {
            if (Session["User"] == null)
            {
                Response.Write("<html><head></head><body><script type='text/javascript'>alert('登录超时,请重新登录');top.location.href='/Login.aspx';</script></body></html>");
                Response.End();
                Response.Flush();
            }
            else
            {
                account = Session["User"] as Zyg.SSO.Core.Business.Account;
            }
        }

        protected void Page_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();


            Response.Redirect(String.Format("~/Err.aspx?msg={0}", Server.HtmlEncode(ex.Message)), true);
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (Request.Cookies["theme"] == null)
            {
                HttpCookie theme = new HttpCookie("theme", "gray");

                Response.Cookies.Add(theme);
            }

            HtmlGenericControl css = new HtmlGenericControl("link");

            css.Attributes.Add("rel", "stylesheet");
            css.Attributes.Add("type", "text/css");
            css.Attributes.Add("href", "/style/reset.css");
            Page.Header.Controls.Add(css);

            css = new HtmlGenericControl("link");
            css.Attributes.Add("rel", "stylesheet");
            css.Attributes.Add("type", "text/css");
            css.Attributes.Add("href", string.Format("/style/{0}/core.css", Request.Cookies["theme"].Value));
            Page.Header.Controls.Add(css);

            base.OnPreRender(e);
        }

        protected void WriteBackScript(string script)
        {
            if (string.IsNullOrEmpty(script))
                return;

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(),
                String.Format("<script type='text/javascript'>{0}</script>", script));
        }
    }
}
